package com.rj.bd.kj.dc.des;

import com.rj.bd.kj.dc.MyAbstractClass;
import com.rj.bd.kj.utils.MyExceptionUtils;

import javax.crypto.*;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;

public class DESDataMaskingService extends MyAbstractClass {

    private static final String ALGORITHM = "DES";
    private SecretKey secretKey;

    /**
     * @desc  构造函数，可以通过初始化密钥来设置
     * @param key
     */
    public DESDataMaskingService(String key)  {
        this.secretKey = new SecretKeySpec(key.getBytes(), ALGORITHM);
    }

    /**
     * @desc  使用KeyGenerator生成密钥
     * @return
     * @throws Exception
     */
    public static String generateKey()  {
        try {

            KeyGenerator keyGen = KeyGenerator.getInstance(ALGORITHM);
            keyGen.init(56); // DES密钥长度固定为56位
            SecretKey secretKey = keyGen.generateKey();
            return Base64.getEncoder().encodeToString(secretKey.getEncoded());

        }catch (Exception e) {
             MyExceptionUtils.handlerExceptions(e);
        }
        return null;
    }


    /**
     * @desc  加密数据
     * @param data
     * @return
     */
    @Override
    public String encrypt(String data)  {
        try {
            Cipher cipher = Cipher.getInstance(ALGORITHM);
            cipher.init(Cipher.ENCRYPT_MODE, secretKey);
            byte[] encryptedBytes = cipher.doFinal(data.getBytes());
            return Base64.getEncoder().encodeToString(encryptedBytes);
        } catch (Exception e) {
           MyExceptionUtils.handlerExceptions(e);
        }
        return data;
    }

    /**
     * @desc  解密数据
     * @param maskedData
     * @return
     */
    @Override
    public String decrypt(String maskedData)  {
        try {
            Cipher cipher = Cipher.getInstance(ALGORITHM);
            cipher.init(Cipher.DECRYPT_MODE, secretKey);
            byte[] decodedBytes = Base64.getDecoder().decode(maskedData);
            byte[] decryptedBytes = cipher.doFinal(decodedBytes);
            return new String(decryptedBytes);
        } catch (Exception e) {
           MyExceptionUtils.handlerExceptions(e);
        }
        return maskedData;
    }
}